package robocup.component.tactics;

import robocup.component.SConf;
import robocup.component.ControllerNumbers.PLAY_MODE;
import robocup.component.ControllerNumbers.STAMINA_LEVEL;
import robocup.component.actionfactories.BasicActionFactory;
import robocup.component.geometry.Vektor;
import robocup.component.situations.SituationEvaluator.TYPE;

public class GoalieKickInState
    extends AbstractState {

  private static final Vektor posToMoveFreeKick1       = new Vektor();

  private static final Vektor posToMoveFreeKick2       = new Vektor();

  private static final Vektor posToMoveBeforeGoalKick1 = new Vektor();

  private static final Vektor posToMoveBeforeGoalKick2 = new Vektor();

  private static final Vektor posToMoveGoalKick        = new Vektor();

  private double        benefit                  = 0;

  // private static boolean debug = false;
  int                   i                        = 0;

  // private double passAngle = 0;

  private int           cycles                   = 0;

  private int           moveCycle                = 0;

  // private int receiverNum = 0;

  private double        neededBenefit            = 0;

  // private Ball dummyBall = null;

  private boolean       foundPass                = false;

  // private ReachableArea gra = new ReachableArea();

  // private SConf sConf = SConf.getInstance();

  /**
   * Construktor Goal-Kick State. Makes the gaolie to kick the ball after
   * catching.
   * 
   * @param parent -
   *          the StateEvaluation
   */
  public GoalieKickInState(
      final StateEvaluation parent) {

    super(parent);
    this.state = STATES.GOALIE_KICK_IN;

  }

  /**
   * Only executable in special play-modes!
   */
  @Override
  public boolean preCondition() {

    return this.checkPlayMode() && (!(this.getWorld().getPlayMode() == PLAY_MODE.FREE_KICK_OWN) || this
        .checkPlayerHasBall()) && this.getWorld().isGoalie();
  }

  /**
   * Action never fails!
   */
  @Override
  protected double successProbability() {

    return 1;
  }

  /**
   * No concurrent actions available up to now!
   */
  @Override
  protected double successBenefit() {

    this.benefit = this.getProphet().getSituationEvaluator().getValue(TYPE.WAIT_WITH_BALL, this
        .getWorld().getMyPosition(), this.getWorld().getMyPosition(), 2, 1,
        this.getWorld().getSelfRef());
  // addition: Dont pass directly after move because of possible WM errors...
    if(this.getWorld().getCycle() < this.moveCycle+2 && this.cycles<185)
      this.benefit = 1;
    
    return this.benefit;
  }

  @Override
  public void calculateMainAction() {

    this.benefit = 0.1;
    GoalieKickInState.posToMoveFreeKick1.x = this.parent.getSConf().half_penalty_width - 2;
    GoalieKickInState.posToMoveFreeKick1.y = SConf.getInstance().GOAL_POS_OWN.y + this.parent
        .getSConf().penalty_length - 2;
    GoalieKickInState.posToMoveFreeKick2.x = -this.parent.getSConf().half_penalty_width + 2;
    GoalieKickInState.posToMoveFreeKick2.y = SConf.getInstance().GOAL_POS_OWN.y + this.parent
        .getSConf().penalty_length - 2;
    if (this.getWorld().getBallRef().getPosition().x < this.getWorld()
        .getMyPosition().x) {
      GoalieKickInState.posToMoveBeforeGoalKick1.x = this.getWorld()
          .getBallRef().getPosition().x + 3;
      GoalieKickInState.posToMoveBeforeGoalKick1.y = this.getWorld()
          .getBallRef().getPosition().y;
    }
    else {
      GoalieKickInState.posToMoveBeforeGoalKick1.x = this.getWorld()
          .getBallRef().getPosition().x - 3;
      GoalieKickInState.posToMoveBeforeGoalKick1.y = this.getWorld()
          .getBallRef().getPosition().y;
    }
    GoalieKickInState.posToMoveBeforeGoalKick2.x = this.getWorld().getBallRef()
        .getPosition().x;
    GoalieKickInState.posToMoveBeforeGoalKick2.y = this.getWorld().getBallRef()
        .getPosition().y - 3;

    GoalieKickInState.posToMoveGoalKick.x = this.getWorld().getBallRef()
        .getPosition().x;
    GoalieKickInState.posToMoveGoalKick.y = this.getWorld().getBallRef()
        .getPosition().y - this.parent.getSConf().BALL_SIZE - this.getWorld()
        .getMyPConf().PLAYER_SIZE - 0.05;
    if (PLAY_MODE.GOAL_KICK_OWN == this.getWorld().getPlayMode()) {
      // System.out.println(getWorld().getCycleAndPlayerString()+" goalie pass
      // benefit: "+getProphet().getPassBenefit());
      if (this.getWorld().getCycle() > this.moveCycle + 3) {
        this.i = 0;
      }
      if (this.i == 0) {
        this.moveCycle = this.getWorld().getCycle();
        this.mainAction = BasicActionFactory.moveToPos(this.getWorld(),
            GoalieKickInState.posToMoveBeforeGoalKick1, STAMINA_LEVEL.HIGH);
        if (this.getWorld().getMyNextPosition().getDistance(
            GoalieKickInState.posToMoveBeforeGoalKick1) < 0.5) {
          this.i = 1;
        }
      }
      else if (this.i == 1) {
        this.moveCycle = this.getWorld().getCycle();
        this.mainAction = BasicActionFactory.moveToPos(this.getWorld(),
            GoalieKickInState.posToMoveBeforeGoalKick2, STAMINA_LEVEL.HIGH);
        if (this.getWorld().getMyNextPosition().getDistance(
            GoalieKickInState.posToMoveBeforeGoalKick2) < 0.5) {
          this.i = 2;
        }
      }
      else if (this.i == 2) {
        this.moveCycle = this.getWorld().getCycle();
        this.mainAction = BasicActionFactory.moveToPos(this.getWorld(),
            GoalieKickInState.posToMoveGoalKick, STAMINA_LEVEL.HIGH);
        if (this.getWorld().getMyNextPosition().getDistance(
            GoalieKickInState.posToMoveGoalKick) < 0.4) {
          this.i = 3;
        }
      }
      else if (this.i == 3) {
        this.moveCycle = this.getWorld().getCycle();
        this.mainAction = BasicActionFactory.turnBodyToPoint(this.getWorld(),
            SConf.getInstance().GOAL_POS_OTHER);
        if (Math.abs(this.getWorld().getBodyAngle()) < 45) {
          this.i = 4;
          this.cycles = 0;
        }
      }
      else if (this.i == 4) {
        if (this.getWorld().getCycle() > this.moveCycle) {
          if (Math.abs(this.getWorld().getBodyAngle()) > 45) {
            this.i = 3;
          }
          this.cycles++;
          if (this.getProphet().canPass() && this.getProphet().getPassBenefit() > 0.10) {
            this.i = 0;
            this.moveCycle = this.getWorld().getCycle();
            this.mainAction = this.getProphet().getPassAction();
          }
        }

        if (this.getWorld().getCycle() > this.moveCycle) {
          if (this.cycles > 90) {
            this.i = 0;
            this.moveCycle = this.getWorld().getCycle();
            if (this.getWorld().getMyPosition().x > 0) {
              this.mainAction = BasicActionFactory.kickFastest(this.getWorld()
                  .getSelfRef(), this.getWorld().getBallRef(), SConf
                  .getInstance().CORNER_RIGHT_OWN);
            }
            else {
              this.mainAction = BasicActionFactory.kickFastest(this.getWorld()
                  .getSelfRef(), this.getWorld().getBallRef(), SConf
                  .getInstance().CORNER_LEFT_OWN);
            }
          }
        }
        this.moveCycle = this.getWorld().getCycle();
      }
    }
    else if (PLAY_MODE.FREE_KICK_OWN == this.getWorld().getPlayMode()) {
      // System.out.println(getWorld().getCycleAndPlayerString()+" goalie pass
      // benefit: "+getProphet().getPassBenefit());
      if (this.getWorld().getCycle() - 3 > this.moveCycle) {
        this.i = 0;
      }
      if (this.getWorld().getCycle() > this.moveCycle) {
        if (this.i == 0) {
          this.moveCycle = this.getWorld().getCycle();
          this.foundPass = false;
          this.mainAction = BasicActionFactory
              .move(GoalieKickInState.posToMoveFreeKick1);
          this.i = 1;
          this.cycles = 0;
        }
      }

      if (this.getWorld().getCycle() > this.moveCycle) {
        if (this.i == 1 && this.cycles < 70) {
          this.moveCycle = this.getWorld().getCycle();
          // neededBenefit= Math.max(Math.min(1, (1 -(cycles *
          // 0.02))),0.5);
          this.neededBenefit = 0.15;
          this.cycles++;
          // find second pass
          // getWorld().setGoalieWMAsMoved(posToMoveFreeKick2);
          // getProphet().calculateNewPass();
          //					
          // if (getProphet().getPassBenefit() >= neededBenefit &&
          // getProphet().canPass()) {
          // debugOut("found pass from 2. freekick pos");
          // foundPass= true;
          // }
          // getWorld().setGoalieBeforeMoved();

          if (this.foundPass) {
            // move
            this.mainAction = BasicActionFactory
                .move(GoalieKickInState.posToMoveFreeKick2);
            this.i = 2;
          }
          else {
            // try direct pass
            if (this.getProphet().canPass() && this.getProphet()
                .getPassBenefit() >= this.neededBenefit) {
              this.mainAction = this.getProphet().getPassAction();
              this.i = 0;
            }
            // turn to field
            else {
              this.mainAction = BasicActionFactory.turnBodyToPoint(this
                  .getWorld(), SConf.getInstance().GOAL_POS_OTHER);
            }
          }
        }
      }

      if (this.getWorld().getCycle() > this.moveCycle) {
        if (this.i == 1 && this.cycles >= 70) {
          this.moveCycle = this.getWorld().getCycle();
          this.cycles++;
          this.mainAction = BasicActionFactory
              .move(GoalieKickInState.posToMoveFreeKick2);
          this.i = 2;
        }
      }

      if (this.getWorld().getCycle() > this.moveCycle) {
        if (this.i == 2 && this.cycles <= 90) {
          this.moveCycle = this.getWorld().getCycle();
          // neededBenefit= Math.max(Math.min(1, (1 -(cycles *
          // 0.02))),0.5);
          this.neededBenefit = 0.15;
          this.cycles++;
          if (this.getProphet().canPass() && this.getProphet().getPassBenefit() >= this.neededBenefit) {
            this.mainAction = this.getProphet().getPassAction();
            this.i = 0;
          }
        }
      }

      if (this.getWorld().getCycle() > this.moveCycle) {
        if (this.i == 2 && this.cycles > 90) {
          this.moveCycle = this.getWorld().getCycle();
          // neededBenefit= Math.max(Math.min(1, (1 -(cycles *
          // 0.02))),0.5);
          this.neededBenefit = 0.15;
          this.cycles++;
          if (this.getWorld().getMyPosition().x > 0) {
            this.mainAction = BasicActionFactory.kickFastest(this.getWorld()
                .getSelfRef(), this.getWorld().getBallRef(), SConf
                .getInstance().CORNER_RIGHT_OWN);
          }
          else {
            this.mainAction = BasicActionFactory.kickFastest(this.getWorld()
                .getSelfRef(), this.getWorld().getBallRef(), SConf
                .getInstance().CORNER_LEFT_OWN);
          }
          this.i = 0;
        }
      }

    }

  }

}

/**
 * $Log: GoalieKickInState.java,v $ Revision 1.17 2006/11/05 13:58:02 wetzker
 * more merging - CLang + MF + some states still missing
 * 
 * Revision 1.16 2006/06/14 23:57:48 gamel come home in freekick without ball
 * 
 * Revision 1.15 2006/06/14 15:35:11 gamel removed some bugs for goalie
 * 
 * Revision 1.14 2006/06/14 00:34:44 gamel if don't know what to do pass to
 * short corner
 * 
 * Revision 1.13 2006/06/13 21:38:57 gamel kick in goalie
 * 
 * Revision 1.12 2006/06/13 21:35:20 phil changed all System.err to System.out
 * 
 * Revision 1.11 2006/05/16 14:08:01 gamel debug output removed
 * 
 * Revision 1.10 2006/05/15 13:13:20 wetzker added new dribbling (by now only
 * wait with ball) added new clear ball adjusted interceptBall (please report
 * bugs) created new AttentionTo- und modified SayModel
 * 
 * Revision 1.9 2006/05/01 19:20:00 gamel lower pass benefit needed
 * 
 * Revision 1.8 2006/05/01 18:47:21 gamel removed usage of body cycle
 * 
 * Revision 1.7 2006/05/01 18:31:19 gamel used bodycycle
 * 
 * Revision 1.6 2006/05/01 18:06:10 gamel debug output
 * 
 * Revision 1.5 2006/04/18 22:46:29 wetzker merged with situationEvaluation
 * branch new: - central situation evaluation for states with ball control -
 * kickNRun situation - ball interception possible when ball kickable - role
 * model for players 6-11(roles are shown in gui, roles not used much for acting
 * yet)
 * 
 * Revision 1.4 2006/04/13 16:36:15 axle changed pass probability (Why must pass
 * probability equals 0.4???)
 * 
 * Revision 1.3.4.2 2006/04/18 21:59:33 wetzker added role model for players
 * 6-11 improved evaluation function
 * 
 * Revision 1.3.4.1 2006/04/17 13:35:21 wetzker *** empty log message ***
 * 
 * Revision 1.3 2006/03/26 21:58:40 wetzker created geometry package and moved
 * geometry classes from worldobject package there
 * 
 * Revision 1.2 2006/03/26 20:09:59 wetzker each player now contains its known
 * states and the playmodes of each state
 * 
 * Revision 1.1 2006/03/13 07:36:33 axle moved from ROOT/src for Maven 2
 * Buildsystem and Team/Soccerscope separation
 * 
 * Revision 1.26 2006/03/07 12:46:13 endert Merge after refactoring: - New
 * State-Interface: One Method for each action type - Action Bean removed -
 * ActionFactorys for helper methods, States calculate main-Action themselves -
 * formatted code - added State-List in Monitor (Context-Menu of Player) - other
 * smaller stuff
 * 
 * Revision 1.25.2.2 2006/02/28 16:58:08 endert Organized imports, outsourced
 * unused vars, removed warnings!
 * 
 * Revision 1.25.2.1 2006/02/28 16:43:11 endert Changed State-Interface:
 * -resetState() -calculateXYAction() Usage of ActionFactories (no higher level
 * actions, these should be calculated in calculateMainAction()), Set
 * getAction() to deprecated and retactoring of variable names (wm ->
 * getWorld())
 * 
 * Revision 1.25 2006/02/24 18:53:47 wetzker used enums for Play_modes and
 * Referee_messages - still has to be improved after creation of new
 * Play_mode-Model - tagged old version removed millions of warnings
 * 
 * Revision 1.24 2006/02/22 23:16:16 wetzker changed SConf access to non-static
 * added some playModes to turnToField for defenders
 * 
 * Revision 1.23 2006/02/22 16:04:30 endert This is done: - Rebound SoccerScope
 * to Agents (can be added or removed in config-file) - Situations now all
 * extend abstract class Situation - Refactorings: ActionBean _ removed from
 * Attributes - SoccerScope will automatically connect to host given in
 * Start-Call - Trainer uses the same host as soccerscope - Removed unused stuff
 * (old confs, bat, etc.) - Code formatted (good luck when merging) - organized
 * imports - all that i forgot to mention here Revision 1.22 2006/02/12 20:31:52
 * gamel set down benefit to 0.4
 * 
 * Revision 1.21 2006/02/12 18:31:39 gamel 1000th bugfix
 * 
 * Revision 1.19 2006/02/12 01:11:03 gamel init state
 * 
 * Revision 1.18 2006/02/11 23:49:30 wetzker commited last patches
 * 
 * Revision 1.16 2006/02/11 20:48:07 gamel no delay now
 * 
 * Revision 1.15 2006/02/11 18:06:14 gamel better kick in and free kick
 * 
 * Revision 1.14 2006/02/10 00:59:32 gamel version without trying to find pass
 * after beaming
 * 
 * Revision 1.13 2006/02/09 22:23:27 gamel changed goalie situation to intercept
 * ball
 * 
 * Revision 1.12 2006/02/09 18:07:14 gamel new "neededBenefit"
 * 
 * Revision 1.11 2006/02/08 21:07:06 gamel kick in works
 * 
 * Revision 1.10 2006/02/08 17:30:24 gamel run free is jetz drinne
 * 
 * Revision 1.9 2006/02/06 20:42:51 endert New Say-Method in Action Bean, which
 * is called after execAcion in StateEvaluation
 * 
 * Revision 1.8 2006/02/06 18:11:14 wetzker refactored, farmatted and cleaned
 * the states Revision 1.7 2006/02/06 17:09:39 endert New Communication merged,
 * bla bla
 * 
 * Revision 1.4 2006/02/03 14:37:22 gamel added Goalie bugfix to HEAD
 * 
 * Revision 1.3.2.2 2006/02/03 14:11:21 gamel added debug output
 * 
 * Revision 1.3.2.1 2006/02/03 13:45:07 gamel kickIn had a bug --> fixed
 * 
 * Revision 1.3 2006/02/03 12:32:46 gamel improved kick in and free kick
 * 
 * free kick could be improved more
 * 
 * Revision 1.2 2006/02/02 22:48:02 gamel added for new goalie
 * 
 * Revision 1.1.2.2 2006/02/02 21:54:14 gamel has to be improved just in
 * test-phase
 * 
 * Revision 1.1.2.1 2005/12/15 23:59:29 gamel new version of goalie splitted
 * into many states and replaced many action-predictions with geometry - there
 * are many bugs inside until now, so beware
 * 
 * Revision 1.9 2005/09/09 12:36:47 endert New Defense (Branch) with simple
 * back-four merged into head!
 * 
 * Revision 1.8 2005/09/08 15:36:16 wetzker improved: -- attackInLine -- Offside --
 * Dribbling added: -- clearball
 * 
 * Revision 1.7 2005/09/01 10:22:49 wetzker + expectedPlayers[] - by now same as
 * allPlayers except for the player that is fastest to ball - if you got
 * information about players behaviour save it here!! corrected collision bug
 * improved passing and ball interception for near balls some changes for a
 * better performance
 * 
 * Revision 1.6 2005/08/16 16:26:35 wetzker merged composite branch
 * 
 * Revision 1.5.2.6 2005/07/29 11:46:34 wetzker debugged NeckRotator
 * 
 * Revision 1.5.2.5 2005/07/18 08:59:56 wetzker debugged: - shootGoal, now
 * working quiet well (but still only a workaround) - attackInLine - bodyCycle()
 * was wrong :/ - dribbling added: - stamina management, use
 * p.correctDashPower(StaminaLevel) moved: - ControllerNumbers, as they aren't
 * use solo by the connection
 * 
 * Revision 1.5.2.4 2005/07/13 21:11:26 wetzker added leadingPass (simple
 * (first) version)
 * 
 * Revision 1.5.2.3 2005/07/13 16:34:17 wetzker *** empty log message ***
 * 
 * Revision 1.5.2.2 2005/07/12 20:12:15 wetzker refactoring in actionbean
 * (mainly the kickActions) - if a kick-method returns 'null' it can't be kicked
 * with the given constraints - new freezeBall (still much to be done) debugging
 * (closeIntercept, getWorld().getPowerForDash (seit 6 Monaten falsch !!)) prob.
 * calculation in directpassState is now basd on correct ballSpeed
 * 
 * Revision 1.5.2.1 2005/07/10 18:30:31 endert reduced successBenefit
 * 
 * Revision 1.5 2005/07/04 23:01:30 glass simple move before kickof inserted
 * 
 * Revision 1.4 2005/06/29 11:45:59 gamel moved Enum STATES from ActionBean to
 * AbstractState
 * 
 * Revision 1.3 2005/06/28 08:38:29 gamel States that use ActionBean, now give
 * themselves as an argument to ActionBean
 * 
 * Revision 1.2 2005/06/15 17:03:06 wetzker removed JIAC from Head + changes in
 * framework please report bugs or shortcomings some scenarios might not work
 * because of wrong imports
 * 
 * Revision 1.1.2.1 2005/06/09 12:31:43 endert Removal of JIAC Libraries and
 * dependencies from project, restructuring the framework and improve some
 * aspects (hoping it is an improvement)
 * 
 * Revision 1.4 2005/05/09 16:55:01 endert New State Framework: Superclass is
 * Abstract State, which is extended by SimpleState and CompositeState. All
 * Other States extend one of them. PlayMode and Conditions are (up to now) not
 * inherited, but can be set in Constructor for some states (PlayModes).
 * Evaluation of States considers postCondition as well.
 * 
 * Revision 1.3 2005/05/09 09:14:05 karlb Added CVS log tag
 * 
 */
